<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <div class="tips">
            <i class="el-icon-info" />
            <span>本月: 社保在缴 公积金在缴</span>
          </div>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <template>
          <el-table
            :data="employeeList"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              :index="editIndex"
              label="序号"
            />
            <el-table-column
              prop="username"
              label="姓名"
            />
            <el-table-column label="头像" width="110">
              <template #default="scope">
                <!-- <img :src="scope.row.staffPhoto" alt="" width="80"> -->
                <el-image :src="scope.row.staffPhoto" class="avatar">
                  <!-- 具名插槽新语法  图片加载出错的时候自动显示 -->
                  <template #error>
                    <!-- <i class="el-icon-picture-outline" /> -->
                    <img src="@/assets/common/bigUserHeader.png" width="80" class="avatar">
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column
              prop="workNumber"
              label="工号"
            />
            <el-table-column
              label="聘用形式"
            >
              <template #default="{row}">
                {{ formOfEmployment(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="departmentName"
              label="部门"
            />
            <el-table-column
              label="入职时间"
            >
              <template #default="{row}">
                {{ formatTime(row.timeOfEntry) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240" fixed="right">
              <template #default="{row}">
                <el-button type="text" size="small" @click="editUser(row.id)">查看</el-button>
                <el-button type="text" size="small" @click="assignRole(row.id)">分配角色</el-button>
                <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <add-employee :dialog-visible="dialogVisible" @close-dialog="closeDialog" @reload="reload" />
    </div>
    <template>
      <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeAssign" @open="openAssignDialog">
        <!-- 这里准备复选框 -->
        <el-checkbox-group v-model="checkLists">
          <el-checkbox v-for="item in checkList" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <template #footer>
          <el-button type="primary" size="small" @click="editPerRole">确定</el-button>
          <el-button size="small" @click="cancel">取消</el-button>
        </template>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { fetchEmployeeAPI, delEmployeeApi } from '@/api/employee'
import addEmployee from './componnents/add-employee.vue'
import { getExportData } from '@/utils/excel'
export default {
  name: 'EmployeeIndex',
  components: { addEmployee },
  data() {
    return {
      checkLists: [],
      dialogVisible: false,
      showRoleDialog: false,
      employeeList: [],
      checkList: [],
      total: 0,
      params: {
        page: 1,
        size: 10
      }
    }
  },
  mounted() {
    this.getEmployeeList()
  },
  methods: {
    // 获取页面数据
    async getEmployeeList() {
      const res = await fetchEmployeeAPI(this.params)
      this.employeeList = res.rows
      this.total = res.total
    },
    // 分页
    changePage(page) {
      this.params.page = page
      this.getEmployeeList()
    },
    editIndex(index) {
      return index + (this.params.page - 1) * this.params.size + 1
    },
    // 修改员工格式
    formOfEmployment(value) {
      const map = {
        1: '正式',
        2: '非正式',
        4: '其他'
      }
      return map[value]
    },
    // 修改时间格式
    formatTime(time) {
      time = dayjs().format('YYYY-MM-DD')
      return time
    },
    // 打开弹框
    addEmployee() {
      this.dialogVisible = true
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false
    },
    // 删除
    delEmployee(id) {
      this.$confirm('确定删除此员工吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployeeApi(id)
        this.getEmployeeList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {

      })
    },
    reload() {
      this.getEmployeeList()
    },
    // 批量导出
    exportExcel() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        const res = await this.$http.get('/sys/user', this.params)
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = []
        const headerRelation = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        // console.log(res)
        const { data } = getExportData(res.rows, headerRelation)
        excel.export_json_to_excel({
          header: Object.keys(headerRelation),
          data: data,
          filename: 'xlsx-list',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 点击跳转
    editUser(id) {
      this.$router.push({
        path: '/detail',
        query: {
          id
        }
      })
    },
    assignRole(id) {
      this.curId = id
      this.showRoleDialog = true
    },
    closeAssign() {
      this.showRoleDialog = false
    },
    cancel() {
      this.closeAssign()
    },
    async openAssignDialog() {
      const res = await this.$http.get('/sys/role', {
        page: 1,
        pagesize: 100
      })
      this.checkList = res.rows
      const list = await this.$http.get(`/sys/user/${this.curId}`)
      this.checkLists = list.roleIds
    },
    async editPerRole() {
      await this.$http.put('/sys/user/assignRoles', {
        id: this.curId,
        roleIds: this.checkLists
      })
      this.$message.success('添加角色权限成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="css">
.avatar{
  width: 70px;
  height: 70px;
  border-radius: 50%;
  object-fit: cover;
}
</style>
